import { h, Component } from 'preact';
import { connect } from 'preact-redux';
import SwipeableViews from 'react-swipeable-views';
import { autoPlay } from 'react-swipeable-views-utils';
import { FStringPrivacy, FTimeStamp } from '~/utils/fliter';
import moment from 'moment';
import history from '~/core/history';
import classNames from 'classnames';
import { Link } from 'preact-router';
import Modal from '~/components/Modal';
import ScrollLoading from '~/components/ScrollLoading';
import Loading from '~/components/Loading';
import { getCooks, cookActionCounts, getMyResume, getMyWorks, favoriteActions, delFavorited, likeActions, delLikeActions } from '~/api/card';
import s from './style.scss';
import prd from './ex.jpg';
import sl from './styleb';

import face from './face.jpg';
import {authUrl, wechatInfo} from '~/config';
import wechat, {share} from '~/utils/wechat';


const AutoPlaySwipeableViews = autoPlay(SwipeableViews);

class Card extends Component {
	constructor(props) {
		super(props);
		this.state = {
			index: 0,
			visible: false,
			showWork: false,
			currectWork: {},
			showResume: false,
			currectResume: {},
			swipe: [1, 2, 3, 4],
			works: [],
			resumelist: [],
			dialogData: '',
			cookId: this.props.user.id || null,
			cardCooksId: null,
			cooksdata: {},
			counts: {},
			myResume: true,
			worksnextpage: 0,
			workscurrentpage: 1,
			resumenextpage: 0,
			resumecurrentpage: 1,
			liked: null,
			favorited: null,
			favoritedId: null,
			likedId: null,
			dialog: false
		};
	}


	componentWillMount() {
		this.setState({
			cardCooksId: this.getUrlType('cookId')
		});
		this.handleGetCooks(this.state.cardCooksId);
		this.getMyWorks(this.state.cardCooksId, 0, 10);
		if (this.props.user.id) {
			this.getCookActionCounts(this.state.cardCooksId, this.props.user.id);
		}
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.user !== this.props.user) {
			this.setState({
				cookId: nextProps.user.id
			});
			this.getCookActionCounts(this.state.cardCooksId, this.state.cookId);
		}
	}

	componentWillUnmount() {
		window.wx.ready(() => {
			share({
				title: wechatInfo.title,
				link: `${authUrl}?state=index_`,
				imgUrl: wechatInfo.imgUrl,
				desc: wechatInfo.desc
			});
		});
	}

	handleSetWxShare = () => {
		window.wx.ready(() => {
			share({
				title: `${this.props.user.name||null}向您推荐了${this.state.cooksdata.name}的名片`,
				link: `${authUrl}?state=share_${this.state.cooksdata.id||null}`,
				imgUrl: this.state.cooksdata.headimgurl || wechatInfo.imgUrl,
				desc: ''
			});
		});
	}

	// 获取url参数
	getUrlType = (name) => {
		const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
		const r = history.location.search.substr(1).match(reg);
		if (r !== null) return unescape(r[2]);
		return null;
	}

	handleGetCooks = (param) => {
		Loading.show();
		getCooks(param).then(res => {
			this.setState({
				cooksdata: res
			});
			this.getResume(this.state.cardCooksId, 0, 10);
			this.handleSetWxShare();
			Loading.hide();
		}).catch(err => {
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
			Loading.hide();
		});
	}

	// 获取厨师社交数据-阅读量、收藏数、点赞数
	getCookActionCounts = (param) => {
		Loading.show();
		cookActionCounts(param).then(res => {
			this.setState({
				counts: res,
				liked: res.isLiked,
				favorited: res.isFavorited,
				favoritedId: res.favoritedId,
				likedId: res.likedId
			});
			Loading.hide();
		}).catch(err => {
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
			Loading.hide();
		});
	}

	handleWorkItem = (item) => () => {
		this.setState({
			showWork: true,
			currectWork: item
		});
	}

	handleResumeItem = (item) => () => {
		this.setState({
			showResume: true,
			currectResume: item
		});
	}

	handelLoading = () => {
		Loading.show();
		setTimeout(() => {
			Loading.hide();
		}, 4000);
	}

	handleChangeIndex = (index) => {
		this.setState({
			index
		});
	}

	handlePage = (n) => () => {
		const length = this.state.swipe.length - 1;
		const { index } = this.state;
		// 👉
		if (n === 1) {
			this.handleChangeIndex(index < length ? index + 1 : 0);
		}
		// 👈
		if (n === 0) {
			this.handleChangeIndex(index > 0 ? index - 1 : length);
		}
	}

	handleClostWorkItem = () => {
		this.setState({
			showWork: false
		});
	}

	handleClostResume = () => {
		this.setState({
			showResume: false
		});
	}

	showDialog = (dialogData) => {
		this.setState(
			{
				visible: true,
				dialogData
			}
    );
	}

	// 关闭提示弹窗
	handerCloseDialog = () => {
		this.setState({
			visible: false,
			dialog: false
		});
	}

	// 作品
	handleWorks = () => {
		this.setState({
			myResume: false
		});
	}

	handleActionWorks = () => new Promise((resolve) => {
		let {cardCooksId, worksnextpage} = this.state;
		this.getMyWorks(cardCooksId, worksnextpage, 10);
		resolve();
	});

	getMyWorks = (cardCooksId, page, size) => {
		// Loading.show();
		getMyWorks(cardCooksId, page, size).then(res => {
			if (res.length >= 1) {
				this.setState({
					works: this.state.works.concat(res),
					worksnextpage: this.state.worksnextpage + 1
				});
			}
			Loading.hide();
		}).catch(err => {
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
			Loading.hide();
		});
	}

	// 资料
	handleResume = () => {
		this.setState({
			myResume: true
		});
	}

	handleActionResume = () => new Promise((resolve) => {
		let {cardCooksId, resumenextpage} = this.state;
		this.getResume(cardCooksId, resumenextpage, 10);
		resolve();
	});

	getResume = (cardCooksId, page, size) => {
		getMyResume(cardCooksId, page, size).then(res => {
			Loading.hide();
			if (res.length >= 1) {
				for (let i=0; i < res.length; i++) {
					switch (res[i].jobTitle) {
						case '0':
							res[i].jobTitle = '水台';
							break;
						case '1':
							res[i].jobTitle = '配菜';
							break;
						case '2':
							res[i].jobTitle = '打荷';
							break;
						case '3':
							res[i].jobTitle = '砧板';
							break;
						case '4':
							res[i].jobTitle = '上杂';
							break;
						case '5':
							res[i].jobTitle = '油鸡';
							break;
						case '6':
							res[i].jobTitle = '尾锅';
							break;
						case '7':
							res[i].jobTitle = '五锅';
							break;
						case '8':
							res[i].jobTitle = '四锅';
							break;
						case '9':
							res[i].jobTitle = '三锅';
							break;
						case '10':
							res[i].jobTitle = '二锅';
							break;
						case '11':
							res[i].jobTitle = '头锅';
							break;
						case '12':
							res[i].jobTitle = '总厨';
							break;
						case '13':
							res[i].jobTitle = '顾问';
							break;
						case '14':
							res[i].jobTitle = '其他';
							break;
					}
				}
				this.setState({
					resumelist: this.state.resumelist.concat(res),
					resumenextpage: this.state.resumenextpage + 1
				});
			}
		}).catch(err => {
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
		});
	}

	// 加入到名片夹
	handleAdd = () => {
		if (!this.props.user.id) {
			this.setState({
				dialog: true
			});
			// history.push('/');
			return;
		}
		Loading.show();
		let { cookId , cardCooksId } = this.state;
		favoriteActions({cookId, favoriteedCook: cardCooksId}).then(res => {
			Loading.hide();
			history.push('/cardholder');
		}).catch(err => {
			Loading.hide();
			if (err.message && err.message === '你已经收藏过！') {
				history.push('/cardholder');
				return;
			}
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
		});

	}

	// 收藏 delFavorited
	handlefavorited = () => {
		Loading.show();
		let { cookId, cardCooksId, favoritedId } = this.state;
		if (this.state.favorited) {
			delFavorited(favoritedId).then(res => {
				this.setState({ favorited: false});
				this.getCookActionCounts(this.state.cardCooksId);
				Loading.hide();
			}).catch(err => {
				this.showDialog({
					dialogTitle: '对不起',
					dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
				});
				Loading.hide();
			});
		} else {
			favoriteActions({cookId, favoriteedCook: cardCooksId}).then(res => {
				this.setState({ favorited: true});
				this.getCookActionCounts(this.state.cardCooksId);
				Loading.hide();
			}).catch(err => {
				this.showDialog({
					dialogTitle: '对不起',
					dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
				});
				Loading.hide();
			});
		}
	}

	// 点赞
	handelLiked = () => {
		Loading.show();
		let { cookId , cardCooksId, likedId } = this.state;
		if (this.state.liked) {
			delLikeActions(likedId).then(res => {
				this.setState({ liked: false});
				this.getCookActionCounts(this.state.cardCooksId);
				Loading.hide();
			}).catch(err => {
				this.showDialog({
					dialogTitle: '对不起',
					dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
				});
				Loading.hide();
			});
		} else {
			likeActions({cookId, likedCook: cardCooksId}).then(res => {
				this.setState({ liked: true});
				this.getCookActionCounts(this.state.cardCooksId);
				Loading.hide();
			}).catch(err => {
				this.showDialog({
					dialogTitle: '对不起',
					dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
				});
				Loading.hide();
			});
		}
	}
	// 去注册
	handerGoCreate = () => {
		this.setState({dialog: false});
		history.push(`/create`);
	}

	render() {
		const { cooksdata, counts, myResume, works, resumelist, liked, favorited } = this.state;
		return (
			<div className={s.root}>
				<div className={classNames(s.wrap, 'center', 'pr')}>
					<div className={s.orbg} />
						<div className="w9 center pdb5-5">
							<div className={s.face}>
								<img src={cooksdata.headimgurl ? cooksdata.headimgurl : face} alt=""/>
							</div>
							<div>
								<div className={s.card}>
									<h3 className="w9 center pdt5">{cooksdata.name}&emsp;<span className={s.score}>综合评分：{cooksdata.points?cooksdata.points:0}</span></h3>
									<ul className={classNames('clearfix', 'nls', 'w9', 'center', s.info)}>
										<li className="w2-5 al-r">电话：</li>
										<li className="w4 font-biggest">{cooksdata.phone}</li>
										<li className="w3-5 al-r"><span className={classNames(s.btnrz, 'icon-v')}>已认证</span></li>
										<li className="w2-5 al-r">现职企业：</li>
										<li className="w7-5">{cooksdata.company ? cooksdata.company : '休息中'}</li>
										<li className="w2-5 al-r">邮箱：</li>
										<li className="w6">{cooksdata.email ? cooksdata.email :'暂无'}</li>
									</ul>
									<div className="w9-8 center clearfix">
										<ul className={classNames(s.banner, 'nls', 'clearfix')}>
											<li className="w3-3-3 txt_cut">
												<span className="icon-hot font-biggest"></span>
												人气:{counts.viewedCount}
											</li>
											{
												this.props.user.id ?
												<li className={classNames('w3-3-3', 'txt_cut', s.bdl)} onClick={this.handelLiked}>
													<span className={`${liked ? 'orange-dark' : ''} icon-zan font-biggest`}></span>
													点赞:{counts.likedCount}
												</li>:
												<li className={classNames('w3-3-3', 'txt_cut', s.bdl)}>
													<span className={`${liked ? 'orange-dark' : ''} icon-zan font-biggest`}></span>
													点赞:{counts.likedCount}
												</li>
											}
											{
												this.props.user.id ?
												<li className={classNames('w3-3-3', 'txt_cut', s.bdl)} onClick={this.handlefavorited}>
													<span className={`${favorited ? 'orange-dark' : ''} icon-fav  font-biggest`}></span>
													收藏:{counts.favoritedCount}
												</li>:
												<li className={classNames('w3-3-3', 'txt_cut', s.bdl)}>
													<span className={`${favorited ? 'orange-dark' : ''} icon-fav  font-biggest`}></span>
													收藏:{counts.favoritedCount}
												</li>
											}
										</ul>
									</div>
								</div>
							</div>
							{
								works.length <= 0 && resumelist.length <= 0 ? null
								: <div className={s.tabinfo}>
									<div className="clearfix">
										<div className={`${myResume ? s.active : null} ${s.item}`} onClick={this.handleResume}>资料</div>
										<div className={`${myResume ? null : s.active} ${s.item}`} onClick={this.handleWorks}>作品</div>
									</div>
									{
										myResume ?
										<div className={classNames(s.list, 'pr')}>
											<ScrollLoading
												handleAction={this.handleActionResume}
												totalsize={10000}
												currentpage={this.state.resumecurrentpage}
												pagesize={10}
											>
												<ul className={`${s.resumelist} nls`} >
													{
														resumelist.length > 0 ? resumelist.map((item, i) => (
															<li className="clearfix" key={i} onClick={this.handleResumeItem(item)}>
																<h3 className="txt_cut font orangered">{moment(item.startDate).format('YYYY-MM-DD')} 到 {item.endDate?moment(item.endDate).format('YYYY-MM-DD'):'至今'}</h3>
																<div className="clearfix">
																	<div className="ww fl txt_cut">
																		企业：{item.company}
																	</div>
																	<div className="ww fr txt_cut">
																		岗位：{item.jobTitle}
																	</div>
																</div>
																<p className="txt_cut gray font-small">{item.content}</p>
															</li>
														)) : <div className="al-c gray pdt1-5">暂无资料~</div>
													}
												</ul>
											</ScrollLoading>
										</div> :
										<div className={classNames(s.list, 'pr')}>
											<ScrollLoading
												handleAction={this.handleActionWorks}
												totalsize={10000}
												currentpage={this.state.workscurrentpage}
												pagesize={10}
											>
												{works.length > 0 ? works.map((item, i) => (
													<div key={i} className={classNames("clearfix", s.prditem)} onClick={this.handleWorkItem(item)}>
														<div className={s.l}>
															<img src={`${item.logo}?x-oss-process=image/resize,m_fill,h_200,w_200`} alt=""/>
														</div>
														<div className={s.r}>
															<h3>{item.title}</h3>
															<p className="txt_cut">{item.content?item.content:'暂无'}</p>
														</div>
													</div>)) : <div className="al-c gray pdt1-5">暂无作品~</div>
												}
											</ScrollLoading>
										</div>
									}
								</div>
							}

							<div className={s.xsrc}>
								<h3>相似人才</h3>
								<div className={classNames('clearfix', s.swbar)}>
									<div className="fl w-5" onClick={this.handlePage(0)}>
										<span className="icon-leftarrow" />
									</div>workcontent
									<div className="fl w9">
										<AutoPlaySwipeableViews
											interval={8000}
											onChangeIndex={this.handleChangeIndex}
											index={this.state.index}
										>
											{
												this.state.swipe.map(item =>
													(<div key={item} className={s.swipeitem}>
														<div>
															<img src={face} alt=""/>
															<p className="al-c">
																{item}name
															</p>
														</div>
														<div>
															<img src={face} alt=""/>
															<p className="al-c">
																name
															</p>
														</div>
														<div>
															<img src={face} alt=""/>
															<p className="al-c">
																name
															</p>
														</div>
														<div>
															<img src={face} alt=""/>
															<p className="al-c">
																name
															</p>
														</div>
													</div>)
												)
											}
										</AutoPlaySwipeableViews>
									</div>
									<div className="fl w-5" onClick={this.handlePage(1)}>
										<span className="icon-rightarrow" />
									</div>
								</div>
							</div>
							<div className="btn mgt-8" onClick={this.handleAdd}>加入到名片夹</div>
						</div>
				</div>
				<Modal
					contentLabel="Modal"
					isOpen={this.state.visible}
					onRequestClose={this.handleHideCard}
					shouldCloseOnOverlayClick={true}
				>
					<div className="pd1 clearfix">
						<h3 className={`al-c pdt1 orange-dark font-bigger`}>{this.state.dialogData.dialogTitle}</h3>
						<p className="pdt1 pdb2 al-c">{this.state.dialogData.dialogContent}</p>
						<div
							onClick={this.handerCloseDialog}
							className="center w6 al-c btn"
						>确定</div>
					</div>
				</Modal>
				<Modal
					contentLabel="Modalb"
					isOpen={this.state.showWork}
					onRequestClose={this.handleClostWorkItem}
				>
					<div className="pd1 clearfix">
						<h3 className="orangered al-c pdt2 pdb-5">{this.state.currectWork.title}</h3>
						<div className="al-c">
							<img className="w5" src={this.state.currectWork.logo} alt=""/>
						</div>
						<div className={`pdt1 ba ${s.workcontent}`}>
							{this.state.currectWork.content}
						</div>
					</div>
				</Modal>
				<Modal
					contentLabel="Modalb"
					isOpen={this.state.showResume}
					onRequestClose={this.handleClostResume}
				>
					<div className="pd1 clearfix">
						<h3 className="orangered al-c pdt2 pdb-5">{this.state.currectResume.title}</h3>
						<div className="clearfix pdb-5 mgb-5" style={{lineHeight: '1.2rem', borderBottom: '1px solid #eee'}}>
							<div className="w4-5 fl al-c orangered">{moment(this.state.currectResume.startDate).format('YYYY-MM-DD')}</div>
							<div className="w1 fl al-c">到</div>
							<div className="w4-5 fl al-c orangered">{this.state.currectResume.endDate?moment(this.state.currectResume.endDate).format('YYYY-MM-DD'):'至今'}</div>
						</div>
						<div className="ww fl pdb-5">公司：{this.state.currectResume.company}</div>
						<div className="ww fl pdb1">职位：{this.state.currectResume.jobTitle}</div>
						<div className={`pdt1 ba`}>
							{this.state.currectResume.content}
						</div>
					</div>
				</Modal>
				<Modal
					contentLabel="Modal"
					isOpen={this.state.dialog}
					onRequestClose={this.handleHideCard}
					shouldCloseOnOverlayClick={true}
				>
				<div className="pd1 clearfix">
					<h3 className={`al-c pdt1 orange-dark fonticon-icon_talk-bigger`}>对不起</h3>
					<p className="pdt1 pdb2 al-c">您还没有名片，请前往创建！</p>
					<div
						onClick={this.handerGoCreate}
						className="fl w4-8 al-c btn"
					>去创建
					</div>
					<div
						onClick={this.handerCloseDialog}
						className="fr w4-8 btnb"
					>取消</div>
				</div>icon-icon_talk
				</Modal>
			</div>
		);
	}
}

function mapStateToProps(state) {
	return {
		user: state.user
	};
}

export default connect(mapStateToProps)(Card);
